<%-- 
    Document   : EnrichNet
    Created on : 20-feb-2014, 9:38:50
    Author     : Juan
--%>

<%@page import="utils.OS"%>
<%@page import="org.apache.commons.fileupload.FileUploadException"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
    <head>
        <%@include file="../disenoWeb/title.html" %>
        <meta charset="utf-8">
        <%@include file="../disenoWeb/head.html" %>
        <script src="../disenoWeb/js/formulario.js" type="text/javascript"></script>	
        <script src="../disenoWeb/js/jquery-ui.min.js"></script>

        <script>

            //When DOM loaded we attach click event to button
            $(document).ready(function() {

                //attach keypress to input
                $('.input').keydown(function(event) {
                    // Allow special chars + arrows 
                    if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9
                            || event.keyCode == 27 || event.keyCode == 13
                            || (event.keyCode == 65 && event.ctrlKey === true)
                            || (event.keyCode >= 35 && event.keyCode <= 39)) {
                        return;
                    } else {
                        // If it's not a number stop the keypress
                        if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                            event.preventDefault();
                        }
                    }
                });

            });

        </script>
        <!--[if lt IE 7]>
    <div style=' clear: both; text-align:center; position: relative;'>
        <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
                <img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today." />
        </a>
    </div>
        <![endif]-->
        <!--[if lt IE 9]>
                    <script type="text/javascript" src="js/html5.js"></script>
            <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen">
            <![endif]-->
    </head>
    <body id="page2">
        <div class="extra">
            <!--==============================header=================================-->
            <header>
                <%@include file="../disenoWeb/divHeader.jsp" %>
                <div class="menu-row">
                    <div class="menu-bg">
                        <div class="main">
                            <nav class="indent-left">
                                <ul class="menu wrapper">
                                    <%@include file="menuEnrichNet.html" %>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
                <div class="row-bot">
                    <div class="center-shadow">
                    </div>
                </div>
            </header>
            <%                /*Se inicializan varias variables*/
                String file1 = "null";//Fichero de la lista de genes (.txt)
                String file2 = "null";//Fichero de la red de genes (.sif)
                String separator = OS.getDirectorySeparator();
                String sesion = session.getId();//Identificador de session

                //----------------------------------------------------------
                /*Se crea una nueva carpeta dedicada a este apartado, llamda "enrichNet". Dentro de esta carpeta
                 se crearan carpetas por usuario mediante el identificador de session*/
                String ubicacionEnrichNet = application.getRealPath(separator
                        + "WEB-INF" + separator + "datos" + separator + "enrichNet");
                File directorio = new File(ubicacionEnrichNet);

                /*Si no existe la carpeta "Enrich" se crea*/
                if (!directorio.exists()) {
                    directorio.mkdir();
                }

                //----------------------------------------------------------
                /*Se crea una carpeta mediante el identificador de session*/
                String ubicacionUsuario = ubicacionEnrichNet + separator + sesion;
                File directorioUsuario = new File(ubicacionUsuario);

                /*Si no existe la carpeta "Enrich" se crea*/
                if (!directorioUsuario.exists()) {
                    directorioUsuario.mkdir();
                }

                //----------------------------------------------------------
                /*Comienza el proceso de subir los archivos indicados por el usuario a la
                 carpeta que se ha creado anteriormente para ello*/
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(1024);
                factory.setRepository(directorioUsuario);

                ServletFileUpload upload = new ServletFileUpload(factory);

                try {
                    List<FileItem> partes = upload.parseRequest(request);

                    int cont = -1;
                    for (FileItem item : partes) {
                        cont++;
                        if (item.getFieldName().equals("file1") || item.getFieldName().equals("file2")) {
                            if (item.getName().equals("") == false) {
                                File file = new File(directorioUsuario, item.getName());
                                item.write(file);

                                /*Se obtiene el fichero .txt*/
                                if (cont == 0) {
                                    file1 = directorioUsuario + separator + item.getName();
                                }/*Se obtiene el fichero .sif*/ else if (cont == 1) {
                                    file2 = directorioUsuario + separator + item.getName();
                                }

                                /*Se elimina el file .txt y el .sif porque si no se elimina da problemas*/
                                if (!file.getPath().endsWith(".txt") && cont == 0) {
                                    file.delete();

                                    String error = "Si";
                                    session.setAttribute("error1", error);
                                } else if (!file.getPath().endsWith(".sif") && cont == 1) {
                                    file.delete();

                                    String error = "Si";
                                    session.setAttribute("error2", error);
                                }

                            }
                        }

                    }

                    if ((session.getAttribute("error1") != null) || (session.getAttribute("error2") != null)) {

                        directorioUsuario.delete();
            %><form action="formEnrichNet.jsp" id="error" ></form>
            <script>submitFormulario();</script>                                                      
            <%
            } else {

            %>
            <section id="content" >
                <div class="content-bg">
                    <div class="main">

            <div id="formulario" >
                <form action="enrichNetRes.jsp" method="post" id="form_select_orgs_goganpa">

                    <br/>

                    <h4> Network Enrichment Statistics: </h4>
                    <select name="stat">
                        <option value="F" selected>FNEA
                        <option value="M" >MNEA    
                    </select>



                    <h4>Specify Functional Gene  </h4>

                    <select name="fgs">
                        <option value="KEGG" selected>KEGG Pathway
                        <option value="Reactome" >Reactome    
                    </select>

                    </br>



                    <h4> Number of permutation: </h4>

                    <input type="number" min="0" name="nperm" class="input" />

                    <br/>
                    <br/>
                    <br/>
                    <br/>
                    <h4> Random seed number: </h4>

                    <input type="number" min="0" name="seed" class="input" />



                    <input type="hidden" name="file1" value="<%=file1%>"/>
                    <input type="hidden" name="file2" value="<%=file2%>"/>

                    <input type="hidden" name="sesion" value="<%=ubicacionUsuario%>"/>
                    <br/>
                    <br/>
                    <button type="submit" value="Enviar" onclick="javascript:muestraLoading();">Accept</button>


                </form>

            </div>

            <div id="imagen-loader-enrich" class="loader" style="display: none">
                <img src="../disenoWeb/images/loader.gif"/>
            </div>

            <%}
                } catch (FileUploadException ex) {
                    out.write("Error al subir archivo " + ex.getMessage());
                }
            %>
<div class="block"></div>
                </div>
            </section>
        </div>


            <!--==============================footer=================================-->
            <footer>
                <%@include file="../disenoWeb/footer.html" %>
            </footer>
            <script type="text/javascript"> Cufon.now();</script>
        </div>
    </body>
</html>
